Let's first create a list
In [6]:
l = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
Let's say I wanted to get only the first four elements of the list. How do we do that?
You can slice a list by specifying the starting index and ending index in the square brackets, separated by a :
In [7]:
first_four = l[0: 4]
print first_four
What if we wanted to get all the elements except the first one?
If you don't specify anything after the :
, python will get everything till the end of the list
In [8]:
second_to_last = l[1:]
print second_to_last
What if you wanted only the last two elements?
Hint: Use the -ve indices :)
In [10]:
print l[-2:]
In [12]:
name = 'Bob The Builder'
print name
Indexing in strings is same as lists or tuples
In [13]:
print name[0]
print name[-1]
print name[2]
Slicing strings is the way to do substring operations in python
In [15]:
print name[0:3]
In [17]:
print name[4:7]
In [18]:
print name [-7: ]
In [ ]: